import random
import re
from datetime import datetime

from flask import abort
from flask import current_app, jsonify
from flask import make_response
from flask import request
from flask import session

from info import redis_store, db
from info.models import User
from info.modules.passport import passport_bul
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from info.utils.yuntongxun.sms import CCP


@passport_bul.route("/logout")
def logout():
    """退出登陆"""
    # 清除session中保存的信息
    session.pop("user_id", None)
    session.pop("nick_name", None)
    session.pop("mobile", None)
    session.pop("is_admin", None)
    return jsonify(errno=RET.OK, errmsg="OK")


@passport_bul.route('/login', methods=["POST"])
def login():
    """登陆"""
    # 获取手机号，密码
    data = request.json
    mobile = data.get("mobile")
    password = data.get("password")
    if not all([mobile, mobile]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    # 根据手机号查看数据库是否有值
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    # 如果有，校验密码
    if not user.check_passowrd(password):
        return jsonify(errno=RET.PWDERR, errmsg="用户名或者密码错误")
    # 保存用户登陆状态
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    # 返回结果
    user.last_login = datetime.now()
    print("登陆成功")
    return jsonify(errno=RET.OK, errmsg="登录成功")
    # return "888"


@passport_bul.route('/register', methods=["POST"])
def register():
    """注册"""
    # 获取参数并判断是否有值
    data = request.json
    mobile = data.get("mobile")
    sms_code = data.get("smscode")
    password = data.get("password")
    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    # 从redis中取出手机号对应的验证码校验
    try:
        real_sms_code = redis_store.get(mobile)
        real_sms_code = real_sms_code.decode()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取本地验证码失败")
    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码过期")
    if sms_code != real_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误")
    # 删除短信验证码
    try:
        redis_store.delete(mobile)
    except Exception as e:
        current_app.logger.error(e)
    # 如果成功，保存手机号，密码到mysql
    # 初始化user模型
    user = User()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = password

    # 记录最后一次登陆时间
    user.last_login = datetime.now()
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据保存错误")
    # 保存当前用户状态
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    # 返回注册结果
    print("注册完成")
    return jsonify(errno=RET.OK, errmsg="OK")


@passport_bul.route('/image_code')
def get_image_code():
    """获取图片验证码"""
    # 1获取随机值
    image_code_id = request.args.get("code_id")
    # 2生成验证码
    if not image_code_id:
        return abort(403)
    name, text, image = captcha.generate_captcha()
    # 3将随机值和验证码文字存如redis
    try:
        redis_store.set("ImageCodeId_" + image_code_id, text, 300)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
    # 4返回数据
    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"
    return response


@passport_bul.route('/sms_code', methods=["POST"])
def send_sms():
    """发送短信"""
    # 获取手机号，用户输入的验证码，随机值
    # print("进来了。。。。。。。")
    data = request.json
    mobile = data.get("mobile")
    image_code = data.get("image_code")
    image_code_id = data.get("image_code_id")

    print("%s==%s==%s" % (mobile, image_code, image_code_id))
    # 校验参数
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if not re.match("^1[3578][0-9]{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号不正确")
    # 从redis中取出数据与用户输入的进行对比
    try:
        real_image_code = redis_store.get("ImageCodeId_" + image_code_id)
        real_image_code = real_image_code.decode()

    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.NODATA, errmsg="数据库获取失败")
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码已过期")
    if real_image_code.upper() != image_code.upper():
        return jsonify(errno=RET.NODATA, errmsg="验证码错误")
    # 生成短信内容，并存入redis
    result = random.randint(0, 999999)
    sms_code = "%06d" % result
    print("短信验证码：==%s==" % sms_code)
    # 发送短信v
    # current_app.logger.debug("短息验证码内容：%s" % sms_code)
    # res = CCP().send_template_sms('15994273196', [sms_code, 5], 1)
    #
    # # 告知短信发送状态并计时
    # if res != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")
    #     # print("失败")
    # else:
    #     # print(666)
    # redis中保存内容
    try:
        redis_store.set(mobile, sms_code, 300)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存短信验证码失败")
    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_bul.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("new/favicon.ico")
